<template>
    <div class="container">
        <Breadcrumb
            :items="['menu.device', 'menu.device.device', 'menu.device.detail']"
        />
        <a-space direction="vertical" :size="16" fill>
            <a-card class="general-card">
                <detail-item
                    :data="deviceInfoData"
                    :title="$t('she-bei-xin-xi')"
                    :loading="deviceInfoLoading"
                    :label-style="{
                        width: '120px',
                        textAlign: 'right',
                        paddingRight: '24px',
                    }"
                    layout="inline-horizontal"
                ></detail-item>
            </a-card>
            <a-card class="general-card" hoverable style="padding: 20px 0 0">
                <a-tabs type="rounded" default-active-key="1">
                    <a-tab-pane
                        key="1"
                        class="detail-tab-pane"
                        :title="$t('she-bei-gui-ge')"
                    >
                        <div
                            style="
                                display: flex;
                                justify-content: flex-end;
                                margin-bottom: 12px;
                            "
                        >
                            <a-button
                                type="primary"
                                @click="openSpecDialog('ADD', {})"
                            >
                                {{ $t('xin-zeng-gui-ge') }}
                            </a-button>
                        </div>
                        <a-table
                            row-key="id"
                            :loading="tableConfig.loading"
                            :columns="tableConfig.columns"
                            :data="tableConfig.data"
                            :bordered="false"
                        >
                            <template #operations="{ record }">
                                <a-button
                                    type="text"
                                    size="small"
                                    @click="openSpecDialog('EDIT', record)"
                                >
                                    {{ $t('edit') }}
                                </a-button>
                                <a-popconfirm
                                    :content="
                                        $t(
                                            'que-ren-shi-fou-shan-chu-gai-gui-ge'
                                        )
                                    "
                                    type="warning"
                                    @ok="deleteSpecProp(record.id)"
                                >
                                    <a-button type="text" size="small">
                                        {{ $t('delete') }}
                                    </a-button>
                                </a-popconfirm>
                            </template>
                        </a-table>
                    </a-tab-pane>
                    <a-tab-pane
                        key="2"
                        class="detail-tab-pane"
                        title="运行状况"
                    >
                        <a-card
                            :bordered="false"
                            :style="{ width: '100%', margin: '10px' }"
                        >
                            <a-card-grid
                                v-for="(runData, index) in runStatusData"
                                :key="index"
                                :hoverable="index % 2 === 0"
                                :style="{ width: '25%', margin: '10px 20px' }"
                            >
                                <a-card
                                    class="card-demo"
                                    :title="runData.name"
                                    :bordered="false"
                                >
                                    <template #extra>
                                        <a-link
                                            :hoverable="false"
                                            @click="fnOpenChartDialog(runData)"
                                            ><chart-line-area
                                                theme="multi-color"
                                                size="16"
                                                :fill="[
                                                    '#2F88FF',
                                                    '#2F88FF',
                                                    '#FFF',
                                                    '#43CCF8',
                                                ]"
                                        /></a-link>
                                    </template>
                                    <p style="font-size: 26px">
                                        {{ runData.value || '--' }}
                                        <span style="font-size: 20px">{{
                                            runData.specs.unit
                                        }}</span>
                                    </p>
                                    <span>{{
                                        runData.occurredTime || '--'
                                    }}</span>
                                </a-card>
                            </a-card-grid>
                        </a-card>
                    </a-tab-pane>
                    <a-tab-pane
                        key="3"
                        class="detail-tab-pane"
                        title="设备告警"
                    >
                        <a-table
                            row-key="id"
                            :loading="deviceAlert.loading"
                            :columns="deviceAlert.columns"
                            :data="deviceAlert.data"
                            :bordered="false"
                            :pagination="pagination"
                            @page-change="onPageChange"
                        >
                            <template #detail="{ record }">
                                <div
                                    v-for="item in record.detail"
                                    :key="item"
                                    class="detail-number"
                                >
                                    {{ item.name }} :<span>{{
                                        item.value
                                    }}</span>
                                </div>
                            </template>
                        </a-table>
                    </a-tab-pane>
                </a-tabs>
            </a-card>
        </a-space>
        <SpecDialog
            :id="specDialogConfig.type === 'EDIT' ? specDialogConfig.id : ''"
            ref="specDialogRef"
            :type="specDialogConfig.type"
            :title="specDialogConfig.title"
            @submit="fetchDeviceSpecData"
        >
        </SpecDialog>
        <DialogChart
            ref="dialogChartRef"
            :identifier="chartDialogConfig.identifier"
            :name="chartDialogConfig.name"
            :title="chartDialogConfig.title"
        >
        </DialogChart>
    </div>
</template>

<script lang="ts" setup>
    import { ref, reactive, nextTick } from 'vue';
    import { get } from 'lodash';
    import { useRoute } from 'vue-router';
    import useLoading from '@/hooks/loading';
    import { useI18n } from 'vue-i18n';
    import DetailItem from '@/components/detail-item.vue';
    import { ChartLineArea } from '@icon-park/vue-next';
    import SpecDialog from './components/spec-dialog.vue';
    import DialogChart from './components/dialog-chart.vue';
    import {
        getDeviceInfo,
        getDeviceSpecList,
        deleteDeviceSpec,
        getDeviceRunStatustList,
        getDeviceAlertList,
    } from './service';
    import { ProductCategoryDict, ProductTypeDict } from '../product/const';

    const { t } = useI18n();
    const { loading: deviceInfoLoading, setLoading: setDeviceInfoLoading } =
        useLoading(true);
    const { query } = useRoute();
    const specDialogRef = ref();
    const dialogChartRef = ref();
    const specDialogConfig = reactive({
        type: 'ADD',
        id: undefined,
        title: t('xin-jian-gui-ge'),
    });
    const chartDialogConfig = reactive({
        title: '历史数据',
        identifier: '',
        name: '',
        occurredTime: undefined,
        specsUnit: '',
    });
    const runStatusData = ref();
    const pagination = reactive({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const tableConfig = reactive({
        loading: false,
        columns: [
            {
                title: t('gui-ge-ming-cheng'),
                dataIndex: 'specName',
            },
            {
                title: t('gui-ge-zhi'),
                dataIndex: 'specValue',
            },
            {
                title: t('device.create.time'),
                dataIndex: 'createTime',
            },
            {
                title: t('geng-xin-shi-jian'),
                dataIndex: 'updateTime',
            },
            {
                title: t('operation'),
                dataIndex: 'operations',
                width: 180,
                slotName: 'operations',
            },
        ],
        data: [],
    });

    const deviceAlert = reactive({
        loading: false,
        columns: [
            {
                title: t('alert.name'),
                dataIndex: 'alertName',
            },
            // {
            //     title: t('device.name'),
            //     dataIndex: 'deviceName',
            // },
            // {
            //     title: t('device.number'),
            //     dataIndex: 'deviceNo',
            // },
            {
                title: t('alert.create.time'),
                dataIndex: 'createTime',
            },
            {
                title: t('alert.detail'),
                dataIndex: 'detail',
                slotName: 'detail',
            },
        ],
        data: [],
    });

    const deviceInfoData = ref([
        {
            label: t('she-bei-bian-ma'),
            path: 'deviceNo',
            value: '',
        },
        {
            label: t('device.name'),
            path: 'deviceName',
            value: '',
        },
        {
            label: t('device.key'),
            path: 'deviceSecret',
            value: '',
        },
        {
            label: t('chan-pin-id-0'),
            path: 'productId',
            value: '',
        },
        {
            label: t('product.name'),
            path: 'productName',
            value: '',
        },
        {
            label: t('product.type'),
            path: 'productCategory',
            formatter(val: string) {
                return ProductCategoryDict[val];
            },
            value: '',
        },
        {
            label: t('device.type'),
            path: 'productType',
            formatter(val: string) {
                return ProductTypeDict[val];
            },
            value: '',
        },
        {
            label: t('zhan-dian-id-0'),
            path: 'stationId',
            value: '',
        },
        {
            label: t('pai-xu'),
            path: 'sort',
            value: '',
        },
    ]);

    function openSpecDialog(type: 'ADD' | 'EDIT', data: any) {
        specDialogConfig.type = type;
        specDialogConfig.id = data.id;
        const params = {
            ...data,
            deviceId: query.id,
        };
        specDialogConfig.title = t('xin-zeng-gui-ge-0');
        if (type === 'EDIT') {
            specDialogConfig.title = t('bian-ji-gui-ge');
            specDialogConfig.id = data.id;
        }
        // 更新数据后再打开弹窗
        nextTick(() => {
            specDialogRef.value.open(params);
        });
    }

    async function deleteSpecProp(id: string) {
        await deleteDeviceSpec({ id });
        // eslint-disable-next-line no-use-before-define
        fetchDeviceSpecData();
    }
    const fnOpenChartDialog = async (row: any) => {
        chartDialogConfig.title = `属性【${row.name}】历史数据`;
        const params = {
            ...row,
            deviceId: query.id,
            title: `【${row.name}】历史数据`,
        };
        // console.log(params);
        nextTick(() => {
            dialogChartRef.value.open(params);
        });
    };

    const fetchDeviceInfoData = async () => {
        try {
            const data = await getDeviceInfo({ id: query.id });
            deviceInfoData.value.forEach((item) => {
                const value = get(data.result, item.path);
                item.value = item.formatter ? item.formatter(value) : value;
            });
        } finally {
            setDeviceInfoLoading(false);
        }
    };
    fetchDeviceInfoData();

    const fetchDeviceSpecData = async () => {
        try {
            tableConfig.loading = true;
            const data = await getDeviceSpecList({ deviceId: query.id });
            tableConfig.data = data.result || [];
        } finally {
            tableConfig.loading = false;
        }
    };
    fetchDeviceSpecData();

    const fetchDeviceRunStatusData = async () => {
        const data = await getDeviceRunStatustList({
            deviceId: query.id,
        });
        runStatusData.value = data.result || [];
    };
    fetchDeviceRunStatusData();

    const fetchDeviceAlertData = async (params: any) => {
        try {
            deviceAlert.loading = true;
            const data = await getDeviceAlertList(params);
            deviceAlert.data = data.result.records;
            pagination.total = data.result.total;
        } finally {
            deviceAlert.loading = false;
        }
    };
    const onPageChange = (pageNum: number) => {
        pagination.current = pageNum;

        fetchDeviceAlertData({
            deviceId: query.id,
            size: pagination.pageSize,
            current: pageNum,
        });
    };

    fetchDeviceAlertData({
        deviceId: query.id,
        size: pagination.pageSize,
        current: 1,
    });
</script>

<style scoped lang="less">
    .container {
        padding: 0 20px 20px;
    }

    .item-container {
        padding-top: 20px;

        :deep(.arco-descriptions-item-label) {
            font-weight: normal;
        }
    }

    .card-demo {
        width: 100%;

        p {
            margin-top: 0;
            font-weight: 500;
            font-size: 18px;
        }

        span {
            color: rgb(var(--gray-6));
        }
    }

    .detail-number {
        display: inline-block;
        font-size: 14px;

        span {
            padding: 0 10px;
            color: red;
            font-weight: 500;
            font-size: 16px;
            white-space: nowrap;
        }
    }

    .card-demo :deep(.arco-card-header) {
        border: none;
    }
</style>
